//
//  String+Add.swift
//  PublicPod
//
//  Created by 许俊华 on 2021/9/6.
//

import Foundation

public extension String {
    /**
     获取一段字符串的range
     */
    func rangeOfSubString(subString:String) -> NSRange {
        
        if XJHUtils.isEmpty(value: subString as AnyObject) {
            return NSMakeRange(0, 0)
        }
        if self.range(of: subString) == nil {
            return NSMakeRange(0, 0)
        }
        let range: Range = self.range(of: subString)!
        let location: Int = self.distance(from: self.startIndex, to: range.lowerBound)
        /* location = 3 */

        let keyLength: Int = self.distance(from: range.lowerBound, to: range.upperBound)
        // let key = "北京"; let keyLength = key.count //count = 2
        /* keyLength = 2 */

        print("location = \(location), length = \(keyLength)")
        /* location = 3, length = 2 */
        return NSMakeRange(location, keyLength)
    }
    
    // 字符串所需要的行数
    func rowOfString(font:UIFont, width:CGFloat) -> Int {
        if self.isEmpty {
            return 0
        }
        
//        CTFontRef myFont = CTFontCreateWithName(( CFStringRef)([font fontName]), [font pointSize], NULL);
        let attStr:NSMutableAttributedString = NSMutableAttributedString.init(string: self)
        attStr.addAttribute(.font, value: font, range: NSMakeRange(0, self.count))
        
        
        let frameSetter:CTFramesetter = CTFramesetterCreateWithAttributedString(attStr)
        let path:CGMutablePath = CGMutablePath.init()
        
        path.addRect(CGRect.init(x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT)))
        
        let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
        
        let lines:NSArray = CTFrameGetLines(frame)
        
        return lines.count;
    }
     
    
    /**
     字符串的高度
     */
    func getLableHeigh(font:UIFont,width:CGFloat) -> CGFloat {
        
        let size = CGSize.init(width: width, height:  CGFloat(MAXFLOAT))
        
        //        let dic = [NSAttributedStringKey.font:font] // swift 4.0
        let dic = [NSAttributedString.Key.font:font] // swift 3.0
        
        let strSize = self.boundingRect(with: size, options: [.usesLineFragmentOrigin], attributes: dic, context:nil).size
        
        return ceil(strSize.height) + 1
    }
    ///获取字符串的宽度
    /*
     计算字符串宽度
     */
    func getLableWidth(font:UIFont,height:CGFloat) -> CGFloat {
        
        let size = CGSize.init(width: CGFloat(MAXFLOAT), height: height)
        
        //        let dic = [NSAttributedStringKey.font:font] // swift 4.0
        let dic = [NSAttributedString.Key.font:font] // swift 3.0
        
        let cString = self.cString(using: String.Encoding.utf8)
        let str = String.init(cString: cString!, encoding: String.Encoding.utf8)
        let strSize = self.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic, context:nil).size
        return strSize.width ?? 0
    }
    
    /// - Parameters:
    ///     - matchStr: 要匹配的字符串
    /// - Returns: 返回所有字符串范围
    @discardableResult
    func hw_exMatchStrRange(_ matchStr: String) -> [NSRange] {
        var selfStr = self as NSString
        var withStr = Array(repeating: "X", count: (matchStr as NSString).length).joined(separator: "") //辅助字符串
        if matchStr == withStr { withStr = withStr.lowercased() } //临时处理辅助字符串差错
        var allRange = [NSRange]()
        while selfStr.range(of: matchStr).location != NSNotFound {
            let range = selfStr.range(of: matchStr)
            allRange.append(NSRange(location: range.location,length: range.length))
            selfStr = selfStr.replacingCharacters(in: NSMakeRange(range.location, range.length), with: withStr) as NSString
        }
        return allRange
    }
    
    //通过对String扩展，字符串增加下表索引功能
    subscript(index:Int) -> String
    {
        get{
            return String(self[self.index(self.startIndex, offsetBy: index)])
        }
        set{
            let tmp = self
            self = ""
            for (idx, item) in tmp.enumerated() {
                if idx == index {
                    self += "\(newValue)"
                }else{
                    self += "\(item)"
                }
            }
        }
    }
    
    /// 截取到任意位置
    func subString(to: Int) -> String {
        let index: String.Index = self.index(startIndex, offsetBy: to)
        return String(self[..<index])
    }
    
    /// 从任意位置开始截取
    func subString(from: Int) -> String {
        let index: String.Index = self.index(startIndex, offsetBy: from)
        return String(self[index ..< endIndex])
    }
    
    /// 从任意位置开始截取到任意位置
    func subString(from: Int, to: Int) -> String {
        let beginIndex = self.index(self.startIndex, offsetBy: from)
        let endIndex = self.index(self.startIndex, offsetBy: to)
        return String(self[beginIndex...endIndex])
    }
    
    //使用下标从任意位置开始截取到任意位置
    public subscript(from: Int, to: Int) -> String {
        let beginIndex = self.index(self.startIndex, offsetBy: from)
        let endIndex = self.index(self.startIndex, offsetBy: to)
        return String(self[beginIndex...endIndex])
    }
}
